package com.gdsz.libbasic.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.gdsz.libbasic.R


class MyTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private var solidColor: Int = 0
    private var strokeColor: Int = 0

    private var radius: Float = 0f
    private var strokeWidth: Float = 0f
    private val shapeDrawable: GradientDrawable
    private val isShape: Boolean

    init {
        val a = context.obtainStyledAttributes(attrs, R.styleable.MyTextView)
        with(a) {
            solidColor = getColor(R.styleable.MyTextView_tvSolidColor, solidColor)
            strokeColor = getColor(R.styleable.MyTextView_tvStrokeColor, strokeColor)
            radius = getDimension(R.styleable.MyTextView_tvRadius, radius)
            strokeWidth = getDimension(R.styleable.MyTextView_tvStrokeWidth, strokeWidth)
            isShape = getBoolean(R.styleable.MyTextView_tv_isShape, true)
            recycle()
        }
        shapeDrawable = GradientDrawable()

    }


    override fun onDraw(canvas: Canvas) {

        // 设置填充颜色
        shapeDrawable.setColor(solidColor) // 设置填充颜色为绿色

        // 设置边框颜色和宽度
        shapeDrawable.setStroke(strokeWidth.toInt(), strokeColor) // 设置边框宽度为5像素，边框颜色为蓝色

        // 设置圆角半径
        shapeDrawable.cornerRadius = radius // 设置圆角半径为20像素
        // 在View上绘制GradientDrawable
        shapeDrawable.setBounds(0, 0, width, height - (strokeWidth / 2).toInt()) // 设置形状的位置和大小
        shapeDrawable.draw(canvas)
        super.onDraw(canvas)
    }


    fun setShape(
        radius: Float = this.radius,
        strokeWidth: Float = this.strokeWidth,
        strokeColor: Int = this.strokeColor,
        solidColor: Int = this.solidColor
    ) {
        this.radius = radius
        this.strokeWidth = strokeWidth
        this.strokeColor = strokeColor
        this.solidColor = solidColor
        invalidate()
    }
}